package com.patchmanage.back.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patchmanage.back.annotation.LoginValidate;
import com.patchmanage.back.annotation.OperLog;
import com.patchmanage.back.entity.PatchGroup;
import com.patchmanage.back.entity.StrategyManage;
import com.patchmanage.back.exception.SystemException;
import com.patchmanage.back.result.CodeMsg;
import com.patchmanage.back.result.Result;
import com.patchmanage.back.service.IPatchGroupService;
import com.patchmanage.back.service.IStrategyManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  策略管理控制器
 * </p>
 *
 * @author huizhao
 * @since 2021-04-04
 */
@Api(value = " 策略管理 controller", tags = {"策略管理 Api"})
@RestController
@RequestMapping("/back/strategy")
public class StrategyManageController {

    @Autowired
    public IStrategyManageService strategyManageService;

    @Autowired
    public IPatchGroupService patchGroupService;

    @Value("${ansible.domain}")
    public String ansibleDomain;

    /**
     * 分页获取策略列表接口
     *
     * @param dict
     * @return
     */
    @ApiOperation(value = "分页获取策略列表接口", notes = "分页获取策略列表接口")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search", value = "search", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "patchDistributeType", value = "patchDistributeType", required = true, dataType = "Integer", paramType = "body"),
            @ApiImplicitParam(name = "pageNo", value = "pageNo", required = true, dataType = "Integer", paramType = "body"),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", required = true, dataType = "Integer", paramType = "body")
    })
    public Result<IPage<StrategyManage>> list(@ApiIgnore @RequestBody Dict dict) {

        Page<StrategyManage> page = new Page(dict.getInt("pageNo"), dict.getInt("pageSize"));
        QueryWrapper<StrategyManage> queryWrapper = new QueryWrapper<>();

        if(dict.getInt("patchDistributeType") == null){
            throw new SystemException(CodeMsg.BIND_ERROR);
        }
        queryWrapper.eq("patch_distribute_type", dict.getStr("patchDistributeType"));

        if(StrUtil.isNotBlank(dict.getStr("search"))){
            queryWrapper.and(wrapper -> wrapper.like("strategy_name", dict.getStr("search"))
//                    .or().like("abs", dict.getStr("search"))
            );
        }
        queryWrapper.orderByDesc("create_time");
        return Result.success(strategyManageService.page(page, queryWrapper));
    }

    /**
     * 获取策略接口
     *
     * @param dict
     * @return
     */
    @ApiOperation(value = "获取策略接口", notes = "获取策略接口")
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer", paramType = "body")
    })
    public Result<StrategyManage> getById(@ApiIgnore @RequestBody Dict dict) {
        return Result.success(strategyManageService.getById(dict.getInt("id")));
    }

    /**
     * 新增或修改策略信息
     * @param strategyManage
     * @return
     */
    @ApiOperation(value = "新增或策略策略信息接口", notes = "新增或修改策略信息接口")
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    @LoginValidate
    @OperLog(operModul="策略管理",operDesc="新增或编辑策略")
    public Result<Boolean> saveOrUpdate(@RequestBody StrategyManage strategyManage) {

        if(StrUtil.isNotBlank(strategyManage.getExecutionTime())){
            JSONObject jsonObject = JSONUtil.parseObj(strategyManage.getExecutionTime());
            Integer mode = jsonObject.getInt("mode");
            if(mode != null && mode == 2){
                Date date = jsonObject.getDate("time");
                if(date != null){
                    jsonObject.set("time", DateUtil.format(date,"HH:mm").toString());
                }
            }
            strategyManage.setExecutionTime(jsonObject.toString());
        }

        if(strategyManage.getPatchGroupId() != null){
           PatchGroup pg =  patchGroupService.getById(strategyManage.getPatchGroupId());
           strategyManage.setPatchGroupName(pg.getName());
        }

        strategyManageService.saveOrUpdate(strategyManage);

        if(strategyManage.getId() != null){
            HttpUtil.get("http://" + ansibleDomain + "/web/modify_strategy?s_id="+strategyManage.getId());
        }

        return Result.success(true);
    }

    /**
     * 删除策略
     * @param dict
     * @return
     */
    @ApiOperation(value = "删除策略接口", notes = "删除策略接口")
    @RequestMapping(value = "removeById", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer", paramType = "body"),
    })
    @LoginValidate
    @OperLog(operModul="策略管理",operDesc="删除策略")
    public Result<Boolean> removeById(@ApiIgnore @RequestBody Dict dict) {
        String id = dict.getStr("id");
        String[] ids = id.split(",");
        HttpUtil.get("http://" + ansibleDomain + "/web/remove_strategy?s_id="+id);
        return Result.success(strategyManageService.removeByIds( Arrays.asList(ids)));
    }

    /**
     * 指定策略执行时间接口
     * @param dict
     * @return
     */
    @ApiOperation(value = "指定策略执行时间接口", notes = "指定策略执行时间接口")
    @RequestMapping(value = "setExecutionTime", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "executionTime", value = "executionTime", required = true, dataType = "String", paramType = "body")
    })
    @OperLog(operModul="策略管理",operDesc="指定策略执行时间")
    public Result<Boolean> setExecutionTime(@ApiIgnore @RequestBody Dict dict) {



        StrategyManage strategyManage = new StrategyManage();
        if(StrUtil.isNotBlank(dict.getStr("executionTime"))){

            JSONObject jsonObject = JSONUtil.parseObj(dict.getStr("executionTime"));
            Integer mode = jsonObject.getInt("mode");
            if(mode != null && mode != 1){
                Date date = jsonObject.getDate("time");
                jsonObject.set("time", DateUtil.format(date,"HH:mm:ss").toString());
            }
            strategyManage.setExecutionTime(jsonObject.toString());
        }

        String ids = dict.getStr("ids");
        List<String> list = Arrays.asList(ids.split(","));

        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.in("id",list);
        return Result.success(strategyManageService.update(strategyManage,updateWrapper));
    }

    /**
     * 开启/关闭策略接口
     * @param dict
     * @return
     */
    @ApiOperation(value = "开启/关闭策略接口", notes = "开启/关闭策略接口")
    @RequestMapping(value = "setStrategyStatus", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "status", value = "status", required = true, dataType = "Integer", paramType = "body")
    })
    @OperLog(operModul="策略管理",operDesc="开启/关闭策略")
    public Result<Boolean> setStrategyStatus(@ApiIgnore @RequestBody Dict dict) {

        StrategyManage strategyManage = new StrategyManage();
        strategyManage.setStatus(dict.getInt("status"));

        String ids = dict.getStr("ids");
        List<String> list = Arrays.asList(ids.split(","));

        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.in("id",list);
        StrategyManage strategy = strategyManageService.getById(ids);

        if (strategy.getInventoryGroupId() == null) {
            return Result.error(CodeMsg.STRATEGY_BIND_INVENTORY_ERROR);
        }

        strategyManageService.update(strategyManage,updateWrapper);

        if(dict.getInt("status") == 1){
            HttpUtil.get("http://" + ansibleDomain + "/web/add_strategy?s_id="+ids);
        }else{
            HttpUtil.get("http://" + ansibleDomain + "/web/remove_strategy?s_id="+strategyManage.getId());
        }
        return Result.success(true);
    }

    /**
     * 执行策略对象接口
     * @param dict
     * @return
     */
    @ApiOperation(value = "执行策略对象接口", notes = "执行策略对象接口")
    @RequestMapping(value = "excuteStrategy", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "strategyId", value = "dtrategyId", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "inventoryGroupId", value = "inventoryGroupId", required = true, dataType = "Integer", paramType = "body")
    })
    @OperLog(operModul="策略管理",operDesc="执行策略对象")
    public Result<Boolean> excuteStrategy(@ApiIgnore @RequestBody Dict dict) {
        StrategyManage strategyManage = new StrategyManage();
        strategyManage.setId(dict.getInt("strategyId"));
        strategyManage.setInventoryGroupId(dict.getInt("inventoryGroupId"));
        return Result.success(strategyManageService.updateById(strategyManage));
    }

}
